// Closure for the main app.
(function() {
  var not_keywords = {'a': null, 'an': null, 'the': null, 'this': null, 'these': null, 'there': null, 'that': null, 'here': null, 'do': null, 'does': null, 'is': null, 'was': null, 'will': null, 'won\'t': null, 'doesn\t': null, 'can': null, 'cannot': null, 'can\'t': null, 'not': null};
  var newest_qaid = $('#newest_qa_id').val() != undefined ? $('#newest_qa_id').val() : -1;
  
  // Converts a string to a comma-separated list of keywords.
  // Primarily used to prepare a search query.
  function stringToKeywords(string) {
    var i, keywords = [], words, word, index = {}, len;
    
    // Convert to lowercase and remove non-alphanumeric characters.
    words = string.toLowerCase().replace(/[^a-z 0-9]+/g, '').split(' ');

    // Look at each individual word.
    for (i=0, len=words.length; i<len; ++i) {
      word = words[i];
      
      // Make sure we haven't already added this keyword and that's it's not an article.
      if (!index.hasOwnProperty('word') && !not_keywords.hasOwnProperty(word)) {
        keywords.push([word, 1]);
        index[word] = keywords.length - 1;
      } else if (index.hasOwnProperty('word') && !not_keywords.hasOwnProperty(word)) {
        ++keywords[index[word]][1];
      }
    }
    
    // Stringify each entry.
    for (i=0, len=keywords.length; i<len; ++i) {
      keywords[i] = keywords[i].join(':');
    }
    
    return keywords.join(',');
  }
  
  // Appends a question to the timeline or qa list.
  function prependQuestion(data) {
    // Parse the JSON.
    var JSONdata = $.parseJSON(data),
    qas = JSONdata['qas'],
    timeline_html = '',
    qabrowse_html = '',
    i = 0,
    len = 0,
    qa = null;
    
    for (i=0, len=qas.length; i<len; ++i) {
      qa = qas[i];
      
      timeline_html = '<li class="hidden">' +
                        '<img src="i/' + qa['profile_pic'] + '" width="78" height="92" alt="Profile Picture" />' +
                        '<p>Q: ' + qa['question'] + '</p>' +
                        '<p>A: ' + qa['answer'] + '</p>' +
                      '</li>';
      qabrowse_html = '<li class="hidden">' + 
              '<p>' + qa['question'] + '</p>' +
              '<p>' + qa['answer'] + '</p>' +
              '<p class="qa-meta">' +
                qa['source'] + '<span>- ' + qa['timestamp'] + '</span>' +
              '</p>' +
            '</li>';
            
      // Insert into the timeline (on the Dashboard).
      $(timeline_html).insertBefore('#timeline li:first');
      $('#timeline li.hidden').fadeIn(1000);
      
      // Insert into the QA browse (on the Repository).
      $(qabrowse_html).insertBefore('#qa-browse li:first');
      $('#qa-browse li.hidden').fadeIn(1000);
    }
    
    // Update the most recent id.
    newest_qaid = JSONdata['lastID'];
    
    // Reset the form.
    $('#question').val('Question');
    $('#answer').val('Answer');
    $('#qa-source').val('Source');
  }
  
  // Handle placeholder text for input fields.  
  // Add focus and blur events to handle showing/hiding the placeholder.
  $("input:text").bind('focus blur', function(event) {
    if($(this).attr("readonly")) return;
    if (event.type == 'focus') {
      // Do we have a placeholder yet?
      if (!$(this).data('placeholder')) {
        $(this).data('placeholder', $(this).val());
      }
    
      if ($(this).val() == $(this).data('placeholder')) {
        $(this).val('');
      }
    } else {
      if ($.trim($(this).val()) == '') {
        $(this).val($(this).data('placeholder'));
      }
    }
  });
  
  // Handles the 'Add a QA' prompt.
  $("#add-qa-prompt").bind('submit', function(event) {
    // Do some nice looking fades.
    $("#add-qa-prompt").fadeOut(350, function() {$("#add-question").fadeIn(600);});
    
    // Prevents the default action (submit).
    return false;
  });

  // Handles adding a QA with Ajax.
  $("#add-question").bind('submit', function(event) {
    // Get the keywords from the question string.
    var keywords = stringToKeywords($('#question').val());
    
    // Ajax submit the question.
    $.ajax({
      "url": 'add-question.php',
      "type": 'POST',
      "data": {"keywords": keywords, "question": $.trim($('#question').val()), "answer": $.trim($('#answer').val()), "source": $.trim($('#qa-source').val()), "lastID": newest_qaid},
      "success": prependQuestion
    });
    
    // Prevent the default action (submit).
    return false;
  });

  
  // Grabs a populated copy of the schedule markup and 
  // replaces the current one with it.
  function schedule(schedule_id)  {
    $.post("schedule.php", { ajax: 1, id: schedule_id },
      function(data){
        $('#schedule').replaceWith(data);
      }
    );
    //prevent submit
    return false;
  }

  // if "previous" button gets pushed we get the schedule 
  // for the prev week
  $("#prev_schedule").live("click", function(event) {
    schedule($("#prev_id").val());
  });

  // if "next" button gets pushed we get the schedule for
  // the next week.
  $("#next_schedule").live("click", function(event) {
    schedule($("#next_id").val());
  });


  // if drop down menu date gets submited we get the schedule
  // for the specified date
  $("#choose-date").bind("submit", function(event) {
    var month = $("#month").val();
    var year = $("#year").val();

    $.post("schedule.php", { ajax: 1, month: month, year: year },
      function(data){
        $('#schedule').replaceWith(data);
      }
    );

    //prevent submit
    return false;
  });

  $(".modify-schedule-form").live("submit",function(event) {
    $(this).attr("id", "changed");
    var theDate = $("#changed > #date").val();
    var theShift = $("#changed > #shift").val();
    var theOldName = $("#changed > #name").val();
    var theOpen= $("#changed > #open").val();
    var ampm= $("#changed > #ampm").val();
    var theOtherName = $("#changed > #other_name").val();
    
    var theForm = this;
    
    if(theOldName == "Open") {
      $.ajax({
        "url": 'manipulate-schedule.php',
        "type": 'POST',
        "data": {'ajax': 1,'get-users':1,'old':theOtherName},
        "success": function(data) {
          var theHTML = 
          "<form id = 'take-shift-form'>" +
          "<input type = 'hidden' id = 'date' name = 'date' value = '" + theDate + "'/>" +
          "<input type = 'hidden' id = 'name' name = 'oldName' value = '" + theOldName + "'/>" +          
          "<input type = 'hidden' id = 'shift' name = 'shift' value = '" + theShift + "'/>" +  
          "<input type = 'hidden' id = 'open' name = 'open' value = '" + theOpen + "'/>" +
          "<input type = 'hidden' id = 'ampm' name = 'ampm' value = '" + ampm + "'/>" +
          data +
          "</form>";       
          $(theForm).replaceWith(theHTML);
          $(this).attr("id", "");
        }
      });
    }
    else {
      $.ajax({
        "url": 'manipulate-schedule.php',
        "type": 'POST',
        "data": {'ajax': 1,'make-open':1,'date':theDate, 'shift':theShift, 'name':theOldName,'open':theOpen, 'ampm': ampm},
        "success": function(data) {
        $("td:has(#changed)").replaceWith(data);
        $(this).attr("id", "");
        }
      });
    }
    return false;
  });
  
  $("#take-shift-form").live("change", function(event) {
    $(this).attr("id", "changed");
    
    var theDate = $("#changed > #date").val();
    var theShift = $("#changed > #shift").val();
    var theOldName = $("#changed > #name").val();
    var theOpen = $("#changed > #open").val();
    var theNewName = $("#changed > #user-drop-down").val();
    var ampm = $("#changed > #ampm").val();
    
    $.ajax({
        "url": 'manipulate-schedule.php',
        "type": 'POST',
        "data": {'ajax': 1,'set-shift':1,'date':theDate, 'shift':theShift, 'name':theOldName,'open':theOpen,'new_name': theNewName, 'ampm': ampm},
        "success": function(data){
            $("td:has(#changed)").replaceWith(data);
            $(this).attr("id", "");
        }  
    });
      
    
    
  });
  

  
  
  
})();

